<template>
  <div class="allocation-permission-layout">
    <div class="left-layout">
      <TablePro
        :columns="userColumns"
        :data="userData"
        :showPage="false"
        :highlight-current-row="true"
        :showTools="false"
        v-loading="userLoading"
        @row-click="rowClickHandler"
      />
      <Pagination
        :total="total"
        v-model:page="pageNum"
        v-model:limit="pageSize"
        @update:page="handlePageChange"
        @update:limit="handlePageSizeChange"
      />
    </div>
    <!-- <div class="left-layout">
    <TablePro :columns="userColumns" :data="userData" :showPage="false" :highlight-current-row="true" :showTools="false"
      v-loading="userLoading" @row-click="rowClickHandler" />
  </div> -->
    <div class="right-layout">
      <TablePro :columns="roleColumns" :data="roleData" :showPage="false" :showTools="false" v-loading="roleLoading" />
    </div>
    <el-dialog v-model="dialogVisible" title="授权" width="800" :before-close="handleClose">
      <el-transfer
        :data="allRoleList"
        v-model="hasRoleList"
        :titles="['所有角色', '拥有角色']"
        :button-texts="['取消授权', '添加授权']"
        :props="{ label: 'roleName', key: 'roleId' }"
        @change="handleChange"
      />
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="savaHasRole" :disabled="isDisabled">确定</el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog v-model="orgDialog" title="组织授权" width="800" :before-close="handleOrgClose" :destroy-on-close="true">
      <TablePro
        ref="orgTableRef"
        row-key="organizationId"
        :columns="orgColumns"
        :data="orgData"
        :showPage="false"
        :showTools="false"
        @selection-change="handleSelectionChange"
      />
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="orgDialog = false">取消</el-button>
          <el-button type="primary" @click="savaHasOrgHandler" :loading="isSavaOrgLoading">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="tsx">
import type { TableProCloumn } from "@/typings";
import type { TransferDirection, TransferKey } from "element-plus";
import { userAutoRoleApi, userListApi, authUserAuthRoleApi } from "@/api";
import { onMounted, ref } from "vue";
import { ElMessage } from "element-plus";
import { useRouter } from "vue-router";
import { useRoleDataStore } from "@/stores";
import { deepCopy } from "@/utils";
import TablePro from "@/components/TablePro/TablePro.vue";
import Pagination from "@/components/pagination/Pagination.vue";

const userLoading = ref<boolean>(false);
const roleLoading = ref<boolean>(false);
const dialogVisible = ref<boolean>(false);
const orgDialog = ref<boolean>(false);
const router = useRouter();
const currentUserId = ref<string>("");
// const currentRole = ref<any>();
const allRoleList = ref<any[]>([]);
const selectOrgIds = ref<string[]>([]);
const isDisabled = ref<boolean>(true);
const orgTableRef = ref();
const hasRoleList = ref<any[]>([]);
const userData = ref<any[]>([]);
const roleData = ref<any[]>([]);
const orgData = ref<any[]>([]);
const userColumns = ref<TableProCloumn[]>([
  {
    label: "用户编号",
    prop: "userId"
  },
  {
    label: "用户名称",
    prop: "userName"
  },
  {
    label: "操作",
    width: 180,
    fixed: "right",
    render: ({ row }) =>
      row.admin ? (
        ""
      ) : (
        <el-button type="primary" link onClick={(e: Event) => permissionRole(row, e)}>
          分配角色
        </el-button>
      )
  }
]);
const roleColumns = ref<TableProCloumn[]>([
  {
    label: "角色ID",
    prop: "roleId"
  },
  {
    label: "角色名称",
    prop: "roleName"
  },
  {
    label: "生效日期",
    prop: "effectiveDate"
  },
  {
    label: "失效日期",
    prop: "expiringDate"
  },
  {
    label: "操作",
    width: 200,
    fixed: "right",
    render: ({ row }) => {
      return (
        <div>
          {/* <el-button type="primary" link onClick={() => handleOrgPermission(row)}>
            分配组织
          </el-button> */}
          {!row.admin && (
            <el-button type="primary" link onClick={() => handleDistribution(row)}>
              分配权限
            </el-button>
          )}
          {/* <el-button type="primary" link onClick={() => handleDistribution(row)}>
            分配权限
          </el-button> */}
        </div>
      );
    }
  }
]);
const orgColumns = ref<TableProCloumn[]>([
  {
    type: "selection",
    width: 60
  },
  {
    type: "index",
    label: "序号",
    width: 80
  },
  {
    label: "组织ID",
    prop: "organizationId"
  },
  {
    label: "组织名称",
    prop: "organizationName"
  }
]);
const params: any = {
  userId: "",
  add: [],
  del: []
};
const isSavaOrgLoading = ref<boolean>(false);

onMounted(() => {
  initUser();
});

const total = ref<number>(0);
const handlePageChange = (page: number) => {
  pageNum.value = page;
  initUser();
};

const handlePageSizeChange = (size: number) => {
  pageSize.value = size;
  initUser();
};
const pageSize = ref<number>(10);
const pageNum = ref<number>(1);
const queryParams = ref<any>({});
const initUser = async () => {
  try {
    const res = await userListApi({ ...queryParams.value, pageNum: pageNum.value, pageSize: pageSize.value });
    if (res.code === 200) {
      userData.value = res.data;
      total.value = res.total as number;
    } else {
      ElMessage.error(res.message);
    }
  } catch (error) {
    console.error("Error fetching data", error);
  }
};

const getRoles = async (userId?: string) => {
  roleLoading.value = true;
  try {
    const result = await userAutoRoleApi(userId as string);
    if (result.code === 200) {
      allRoleList.value = result.data.roles;
      roleData.value = result.data.user.roles;
      hasRoleList.value = result.data.user.roles;
    } else {
      ElMessage.error(result.message ? result.message : "获取角色失败");
    }
  } catch (error) {
    ElMessage.error("获取角色异常，请稍后再试！");
  } finally {
    roleLoading.value = false;
  }
};

// 用户授权
const permissionRole = async (row: any, event: Event) => {
  event && event.stopPropagation();
  currentUserId.value = row.userId;
  await getRoles(row.userId);
  const showList = allRoleList.value.filter((item: any) => hasRoleList.value.some((role: any) => role.roleId === item.roleId));
  const ids: string[] = [];
  showList.forEach((item: any) => {
    ids.push(item.roleId);
  });
  hasRoleList.value = ids;
  dialogVisible.value = true;
};

const useRoleData = useRoleDataStore();
const handleDistribution = (row: any) => {
  useRoleData.roleData = { ...row };
  router.push({ name: "systemRolePerssionRole", params: { roleId: row.roleId } });
};

// 点击用户列表获取角色列表
const rowClickHandler = (row: any) => {
  currentUserId.value = row.userId;
  getRoles(row.userId);
};

// const handleOrgPermission = async (row: any) => {
//   orgDialog.value = true;
//   currentRole.value = row;
//   try {
//     const result = await getOrgListByRoleId(row.roleId);
//     if (result.code === 200 && result.data.length > 0) {
//       currentRoleOrg.value = result.data;
//       orgData.value.forEach((item: any) => {
//         if (!orgTableRef.value) return;
//         orgTableRef.value.tablePro.toggleRowSelection(
//           item,
//           result.data.some((z: any) => item.organizationId === z.organizationId)
//         );
//       });
//     }
//   } catch (error) {
//     ElMessage.error("获取组织信息异常");
//   }
// };

const savaHasRole = async () => {
  try {
    params.userId = currentUserId.value;
    const result = await authUserAuthRoleApi({ userId: currentUserId.value, roleIds: hasRoleList.value.join(",") });

    if (result.code === 200) {
      ElMessage.success("授权成功");
      initUser();
    } else {
      ElMessage.error(result.message);
    }
  } catch (error) {
    ElMessage.error("授权失败，请稍后再试");
  } finally {
    params.add = [];
    params.del = [];
    dialogVisible.value = false;
  }
};

const handleSelectionChange = (values: any[]) => {
  const list = deepCopy(values);
  const ids: string[] = [];
  list.forEach((item: any) => {
    ids.push(item.organizationId);
  });
  selectOrgIds.value = ids;
};

const savaHasOrgHandler = async () => {
  // try {
  //   isSavaOrgLoading.value = true;
  //   const params: any = {
  //     userId: currentUserId.value,
  //     roleId: currentRole.value.roleId,
  //     add: [],
  //     del: []
  //   };
  //   selectOrgIds.value.forEach((item: any) => {
  //     const result = currentRoleOrg.value.some((z: any) => z.organizationId === item);
  //     if (!result) {
  //       params.add.push(item);
  //     }
  //   });
  //   currentRoleOrg.value.forEach((item: any) => {
  //     const result = selectOrgIds.value.some((z: any) => z === item.organizationId);
  //     if (!result) {
  //       params.del.push(item.organizationId);
  //     }
  //   });
  //   const result = await addRoleOrganizationApi(params);
  //   if (result.code === 200) {
  //     ElMessage.success("授权成功");
  //     selectOrgIds.value = [];
  //     initUser();
  //     initAllRole();
  //   } else {
  //     ElMessage.error(result.message);
  //   }
  // } catch (error) {
  //   ElMessage.error("授权失败，请稍后再试");
  // } finally {
  //   orgDialog.value = false;
  //   isSavaOrgLoading.value = false;
  // }
};

const handleChange = (value: TransferKey[], direction: TransferDirection, movedKeys: TransferKey[]) => {
  isDisabled.value = false;
  if (direction === "right") {
    params.add = movedKeys;
  }
  if (direction === "left") {
    params.del = movedKeys;
  }
};

const handleClose = (done: () => void) => {
  done();
};

const handleOrgClose = (done: () => void) => {
  done();
};
</script>

<style scoped lang="scss">
.allocation-permission-layout {
  // border: 1px solid blue;
  // border: none;
  width: 100%;
  height: 90%;
  display: flex;
  // justify-content: space-around;

  .left-layout,
  .right-layout {
    flex: 1;
  }
  .right-layout {
    width: 50%;
    // border: 1px solid green;
  }

  .left-layout {
    // border: 1px solid red;
    margin-right: 10px;
    // margin-left: 10px
  }
}
</style>
